{% extends "base_lite.html" %}

{% block title %}管理员面板{% endblock %}

{% block additional_styles %}
<style>
/* 上传区域样式 */
.upload-area {
    border: 3px dashed var(--border);
    border-radius: 12px;
    padding: 3rem 2rem;
    text-align: center;
    transition: all 0.3s ease;
    background: rgba(var(--primary-rgb), 0.02);
    cursor: pointer;
}

.upload-area:hover, .upload-area.dragover {
    border-color: var(--primary);
    background: rgba(var(--primary-rgb), 0.05);
    transform: translateY(-2px);
}

.upload-area.uploading {
    border-color: var(--warning);
    background: rgba(255, 193, 7, 0.1);
}

/* 图片网格样式 */
.image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 1rem;
    margin-top: 2rem;
}

.image-card {
    background: var(--card-bg);
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    position: relative;
    border: 1px solid var(--border);
}

.image-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.image-thumbnail {
    width: 100%;
    height: 150px;
    object-fit: cover;
    background: #f8f9fa;
}

.image-info {
    padding: 1rem;
}

.progress-bar {
    width: 100%;
    height: 6px;
    background: var(--border);
    border-radius: 3px;
    overflow: hidden;
    margin: 1rem 0;
}

.progress-fill {
    height: 100%;
    background: linear-gradient(90deg, var(--primary), var(--secondary));
    border-radius: 3px;
    transition: width 0.3s ease;
    width: 0%;
}

/* 状态卡片动画 */
.stat-card {
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-3px);
}

/* 删除确认模态框 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.7);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.modal-content {
    background: var(--card-bg);
    padding: 2rem;
    border-radius: 12px;
    max-width: 400px;
    margin: 1rem;
    text-align: center;
}
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">📊 管理员面板</h2>
        <div class="d-flex gap-2">
            <a href="{{ url_for('user_gallery') }}" class="btn btn-outline btn-sm">
                🖼️ 图片库
            </a>
            <a href="{{ url_for('logout') }}" class="btn btn-secondary btn-sm">
                🚪 退出
            </a>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid mb-4">
        <div class="stat-card">
            <div class="stat-icon">📷</div>
            <div class="stat-number" id="total-images">{{ stats.total_images }}</div>
            <div class="stat-label">总图片数</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">💾</div>
            <div class="stat-number" id="total-size">{{ stats.total_size_mb }}MB</div>
            <div class="stat-label">总存储</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">📅</div>
            <div class="stat-number" id="uploaded-today">{{ stats.uploaded_today }}</div>
            <div class="stat-label">今日上传</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">⚡</div>
            <div class="stat-number">{{ stats.avg_file_size_mb }}MB</div>
            <div class="stat-label">平均大小</div>
        </div>
    </div>

    <!-- 上传区域 -->
    <div class="card mb-4">
        <h5 class="card-title mb-3">
            📤 上传图片
        </h5>
        
        <div class="upload-area" id="uploadArea" onclick="document.getElementById('fileInput').click()">
            <div style="font-size: 4rem; margin-bottom: 1rem; opacity: 0.6;">📁</div>
            <h5 class="fw-bold mb-2">点击或拖拽文件到此处上传</h5>
            <p class="text-muted mb-0">支持 JPG、PNG、GIF 格式，单个文件不超过 10MB</p>
            <div class="progress-bar" id="progressBar" style="display: none;">
                <div class="progress-fill" id="progressFill"></div>
            </div>
        </div>
        
        <input type="file" id="fileInput" multiple accept="image/*" style="display: none;">
        
        <div id="uploadStatus" class="mt-3" style="display: none;"></div>
    </div>

    <!-- 图片管理 -->
    <div class="card">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="card-title mb-0">
                🗂️ 图片管理 <span class="badge" id="image-count">{{ images|length }}</span>
            </h5>
            <div class="d-flex gap-2">
                <button class="btn btn-outline btn-sm" onclick="refreshImages()">
                    🔄 刷新
                </button>
                <input type="text" class="form-control" placeholder="🔍 搜索图片..." 
                       style="width: 200px;" onkeyup="filterImages(this.value)">
            </div>
        </div>

        <div class="image-grid" id="imageGrid">
            {% for image in images %}
            <div class="image-card" data-filename="{{ image.filename }}">
                <img src="{{ url_for('thumbnail_file', filename=image.thumbnail) }}" 
                     alt="{{ image.filename }}" class="image-thumbnail"
                     onerror="this.src=''">
                <div class="image-info">
                    <div style="font-size: 0.875rem; font-weight: 600; margin-bottom: 0.5rem; word-break: break-all;">
                        {{ image.filename }}
                    </div>
                    <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 0.5rem;">
                        📏 {{ image.width }}×{{ image.height }} | 💾 {{ "%.1f"|format(image.size / 1024 / 1024) }}MB
                    </div>
                    <div style="font-size: 0.75rem; color: var(--text-muted); margin-bottom: 1rem;">
                        📅 {{ image.upload_time.strftime('%Y-%m-%d %H:%M') }}
                    </div>
                    <div class="d-flex gap-2">
                        <button class="btn btn-primary btn-sm flex-1" 
                                onclick="viewImage('{{ image.filename }}')">
                            👁️ 查看
                        </button>
                        <button class="btn btn-danger btn-sm" 
                                onclick="confirmDelete('{{ image.filename }}')">
                            🗑️ 删除
                        </button>
                    </div>
                </div>
            </div>
            {% else %}
            <div style="grid-column: 1 / -1; text-align: center; padding: 3rem; color: var(--text-muted);">
                <div style="font-size: 4rem; margin-bottom: 1rem; opacity: 0.5;">📭</div>
                <h5>暂无图片</h5>
                <p>上传您的第一张图片开始使用吧！</p>
            </div>
            {% endfor %}
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal-overlay" id="deleteModal">
    <div class="modal-content">
        <div style="font-size: 3rem; margin-bottom: 1rem;">⚠️</div>
        <h5 class="fw-bold mb-3">确认删除</h5>
        <p class="mb-4">确定要删除图片 <strong id="deleteFileName"></strong> 吗？此操作无法撤销。</p>
        <div class="d-flex gap-2 justify-content-center">
            <button class="btn btn-secondary" onclick="closeDeleteModal()">取消</button>
            <button class="btn btn-danger" onclick="deleteImage()" id="confirmDeleteBtn">删除</button>
        </div>
    </div>
</div>

<script>
let currentDeleteFile = null;

// 文件上传功能
document.getElementById('fileInput').addEventListener('change', handleFileUpload);

// 拖拽上传
const uploadArea = document.getElementById('uploadArea');
uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('dragover');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    const files = e.dataTransfer.files;
    uploadFiles(files);
});

function handleFileUpload(e) {
    uploadFiles(e.target.files);
}

function uploadFiles(files) {
    if (files.length === 0) return;
    
    const formData = new FormData();
    for (let file of files) {
        formData.append('file', file);
    }
    
    const progressBar = document.getElementById('progressBar');
    const progressFill = document.getElementById('progressFill');
    const uploadStatus = document.getElementById('uploadStatus');
    const uploadArea = document.getElementById('uploadArea');
    
    // 显示进度条
    progressBar.style.display = 'block';
    uploadArea.classList.add('uploading');
    uploadStatus.style.display = 'block';
    uploadStatus.innerHTML = '<div style="color: var(--warning);">📤 正在上传...</div>';
    
    const xhr = new XMLHttpRequest();
    
    xhr.upload.addEventListener('progress', (e) => {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            progressFill.style.width = percentComplete + '%';
        }
    });
    
    xhr.onload = function() {
        uploadArea.classList.remove('uploading');
        progressBar.style.display = 'none';
        progressFill.style.width = '0%';
        
        if (xhr.status === 200) {
            const response = JSON.parse(xhr.responseText);
            if (response.success) {
                uploadStatus.innerHTML = '<div style="color: var(--success);">✅ 上传成功！</div>';
                setTimeout(() => {
                    uploadStatus.style.display = 'none';
                    window.location.reload();
                }, 2000);
            } else {
                uploadStatus.innerHTML = '<div style="color: var(--danger);">❌ 上传失败：' + response.message + '</div>';
            }
        } else {
            uploadStatus.innerHTML = '<div style="color: var(--danger);">❌ 上传失败，请重试</div>';
        }
    };
    
    xhr.onerror = function() {
        uploadArea.classList.remove('uploading');
        progressBar.style.display = 'none';
        uploadStatus.innerHTML = '<div style="color: var(--danger);">❌ 网络错误，请重试</div>';
    };
    
    xhr.open('POST', '{{ url_for("upload_image") }}');
    xhr.send(formData);
}

// 图片操作
function viewImage(filename) {
    window.open('{{ url_for("uploaded_file", filename="") }}' + filename, '_blank');
}

function confirmDelete(filename) {
    currentDeleteFile = filename;
    document.getElementById('deleteFileName').textContent = filename;
    document.getElementById('deleteModal').style.display = 'flex';
}

function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
    currentDeleteFile = null;
}

function deleteImage() {
    if (!currentDeleteFile) return;
    
    const confirmBtn = document.getElementById('confirmDeleteBtn');
    confirmBtn.textContent = '删除中...';
    confirmBtn.disabled = true;
    
    fetch('{{ url_for("delete_image_api") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ filename: currentDeleteFile })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            closeDeleteModal();
            // 移除对应的图片卡片
            const imageCard = document.querySelector(`[data-filename="${currentDeleteFile}"]`);
            if (imageCard) {
                imageCard.remove();
            }
            // 更新统计
            updateStats();
            showMessage('删除成功！', 'success');
        } else {
            showMessage('删除失败：' + data.message, 'danger');
        }
    })
    .catch(error => {
        showMessage('网络错误，请重试', 'danger');
    })
    .finally(() => {
        confirmBtn.textContent = '删除';
        confirmBtn.disabled = false;
    });
}

// 搜索过滤
function filterImages(query) {
    const imageCards = document.querySelectorAll('.image-card');
    const searchTerm = query.toLowerCase();
    
    imageCards.forEach(card => {
        const filename = card.dataset.filename.toLowerCase();
        if (filename.includes(searchTerm)) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}

// 刷新图片
function refreshImages() {
    window.location.reload();
}

// 更新统计信息
function updateStats() {
    fetch('{{ url_for("get_stats") }}')
    .then(response => response.json())
    .then(data => {
        document.getElementById('total-images').textContent = data.total_images;
        document.getElementById('total-size').textContent = data.total_size_mb + 'MB';
        document.getElementById('uploaded-today').textContent = data.uploaded_today;
        document.getElementById('image-count').textContent = data.total_images;
    });
}

// 显示消息
function showMessage(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type}`;
    alertDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1001;
        max-width: 300px;
        animation: slideIn 0.3s ease;
    `;
    alertDiv.innerHTML = `
        <div style="display: flex; align-items: center; gap: 0.5rem;">
            ${type === 'success' ? '✅' : '❌'} ${message}
        </div>
    `;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}

// 点击模态框外部关闭
document.getElementById('deleteModal').addEventListener('click', (e) => {
    if (e.target === e.currentTarget) {
        closeDeleteModal();
    }
});
</script>
{% endblock %}
